package com.wang.tool.lock.aop;

import com.wang.tool.cache.aop.CacheAdvisorOrder;
import com.wang.tool.lock.LockConfigCenter;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;

/**
 * @Description
 * @Author shaopeng
 * @Date 2022/7/23
 * @Version 1.0
 */
public class LockRegister implements ImportBeanDefinitionRegistrar {

    private static final String SPRING_LOCK_KEY_BUILDER_NAME = "springLockKeyBuilder";
    public static final String SPRING_LOCK_DYNAMIC_CONFIG_CENTER_NAME = "springLockDynamicConfigCenter";


    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        AnnotationAttributes cacheAttr = AnnotationAttributes.fromMap(importingClassMetadata.getAnnotationAttributes(EnableLock.class.getName()));
        int order = cacheAttr.getNumber("order");
        BeanDefinitionBuilder orderBuilder = BeanDefinitionBuilder.genericBeanDefinition(CacheAdvisorOrder.class);
        orderBuilder.addPropertyValue("order", order);
        registry.registerBeanDefinition("lockAdvisorOrder1", orderBuilder.getBeanDefinition());


        //keyBuilder
        BeanDefinitionBuilder keyBuilder = BeanDefinitionBuilder.genericBeanDefinition(cacheAttr.getClass("keyBuilder"));
        registry.registerBeanDefinition(SPRING_LOCK_KEY_BUILDER_NAME, keyBuilder.getBeanDefinition());

        //dynamicConfigCenter
        BeanDefinitionBuilder configCenter = BeanDefinitionBuilder.genericBeanDefinition(cacheAttr.getClass("dynamicConfigCenter"));
        registry.registerBeanDefinition(SPRING_LOCK_DYNAMIC_CONFIG_CENTER_NAME, configCenter.getBeanDefinition());

        LockConfigCenter.setDefLockWaitTime(cacheAttr.getNumber("defLockWaitTime"));
        LockConfigCenter.setDefLockSecond(cacheAttr.getNumber("defLockSecond"));
    }
}
